<template>
    <div class="add-container">
        <div class="form-container">
            <el-form :model="formParam" :rules="rules" ref="custForm">
                <el-form-item label="Client Code" label-width="220px" prop="clientCode" required>
                    <el-select v-model="formParam.clientCode" filterable clearable placeholder="choose">
                        <el-option :key="item.clientCode" :label="item.clientCode" :value="item.clientCode"
                            v-for="item in clients">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="Carrier Code" label-width="220px" prop="carrierCode" required>
                    <el-select v-model="formParam.carrierCode" filterable clearable placeholder="choose">
                        <el-option :key="item.carrierCode" :label="item.carrierCode" :value="item.carrierCode"
                            v-for="item in carriers">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="Vessel Name" label-width="220px" prop="vesselName" required>
                    <el-select v-model="formParam.vesselName" filterable clearable placeholder="choose" @change="selectVessel" >
                        <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName"
                            v-for="item in vessels">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="Voyage" label-width="220px" prop="voyageNo" required>
                    <el-select v-model="formParam.voyageNo" filterable clearable placeholder="choose" v-if="!isFreight">
                        <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo"
                            v-for="item in voyages" />
                    </el-select>
                    <el-input v-else style="width: 218px;"  v-model="formParam.voyageNo"  placeholder="Voyage No" ></el-input>
                </el-form-item>
                <!-- <el-form-item label="Choose Template" label-width="220px" prop="templateType" required>
                    <el-select v-model="formParam.templateType" filterable placeholder="choose">
                        <el-option :key="index" :label="item" :value="index"
                            v-for="(item,index) in templateTypes">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="Date" label-width="220px" prop="year" required>
                    <el-date-picker v-model="formParam.year" type="year" placeholder="Pick a year" />
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="cancel">{{ $t("ship.button.cancel") }}</el-button>
                <el-button type="primary" :loading="isLoading" @click="submitApplyForm">Apply</el-button>
            </div>
            <div class="booking-no">
                <span style="padding-right: 8px">Fixture No：</span>
                <el-link class="fixtureNo" type="primary" @click="toFixtureDetail">{{ formParam.fixtureNo || ""
                    }}</el-link>
                <el-icon v-if="formParam.fixtureNo">
                    <DocumentCopy @click="copyText(formParam.fixtureNo || '123')" />
                </el-icon>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { ref, onMounted, reactive, toRefs } from "vue";
    import service from "@/utils/request";
    import { ElMessage } from "element-plus";
    import moment from "moment";
    import { useRouter, useRoute } from "vue-router";
    const router = useRouter();
    const route = useRoute();
    let clients = reactive([])
    let carriers = reactive([] as any);
    let vessels = reactive([] as any);
    let voyages = reactive([] as any)
    const isFreight = ref(false)
    watch(
        route,
        () => {
            isFreight.value = route.query.isFreight
        },
        { immediate: true, deep: true }
    )
    const formParam = reactive({
        clientCode: null,
        clientName: null,
        clientId: null,
        year: String(new Date().getFullYear()),
        templateType: null,
        carrierCode: null,
        vesselName: null,
        voyageNo: null,
        fixtureNo: null,
        carrierName: null,
        type: isFreight.value ? 1 : 0,
    })
    const rules = {
        clientCode: [{ required: true, message: "Client Code cann't be blank", trigger: "blur" }],
        carrierCode: [{ required: true, message: "Carrier Code cann't be blank", trigger: "blur" }],
        vesselName:  [{ required: true, message: "Vessel Name cann't be blank", trigger: "blur" }],
        voyageNo:  [{ required: true, message: "Voyage cann't be blank", trigger: "blur" }],
        year: [{ required: true, message: "year can't be null", trigger: "blur" }]
    }

    const templateTypes = ["Standard", "AICC"]


    onMounted(async () => {
        let result = await service.get("/shipping/client/list");
        if (result) {
            clients = result.data
        }
        result = await service.get("/shipping/carrier/list");
        if (result) {
            carriers = result.data
        }
        result = await service.get("/shipping/schedule/getAllSchedule");
        if (result) {
            vessels = result.data
        }
    })

    // 提交申请
    const isLoading = ref(false);
    const custForm = ref();
    const submitApplyForm = () => {
        custForm.value.validate(async valid => {
            if (valid) {
                if (isLoading.value) return;
                isLoading.value = true;
                let carrierIndex = carriers.findIndex(item => item.carrierCode == formParam.carrierCode)
                formParam.carrierName = carriers[carrierIndex].carrierName
                let clientIndex = clients.findIndex(item => item.clientCode == formParam.clientCode)
                formParam.clientName = clients[clientIndex].fullName
                formParam.clientId = clients[clientIndex].clientId
                formParam.year = moment(formParam.year).format('YYYY')
                service
                    .post("/shipping/fixtureNote/apply", formParam)
                    .then(result => {
                        if (result && result.data) {
                           Object.keys(result.data).forEach(key => {
                               formParam[key] = result.data[key];
                           });
                        }
                    })
                    .finally(() => {
                        isLoading.value = false;
                    });
            }
        });
        //reset();
        //isTable.value=true
    };
    //表单重置
    function reset() {
        const params = {
            clientCode: null,
            date: String(new Date().getFullYear()),
            carrierCode: null,
            fixtureNo: null,
            carrierName: null
        };
        Object.keys(params).forEach(key => {
            formParam[key] = params[key];
        });
    }
    const cancel = () => {
        if (isFreight.value) {
            router.push({ path: "/freightForward/fixtureNote/list" });
        } else {
            router.push({
                path: "/contract/fixtureNote", query: {
                    fixtureNo: formParam.fixtureNo,
                    // carrierCode: formParam.carrierCode,
                    // clientCode: formParam.clientCode,
                }
            });
        }
        reset()
    }


    const selectVessel = async () => {
        //@ts-ignore
        let item = vessels.find(n => n.vesselName == formParam.vesselName)
        voyages = item.schedules
    }

    const toFixtureDetail = () => {
        if (formParam.fixtureNo) {
            if (formParam.templateType == 1) {
                localStorage.setItem("RECORD_DATA1", JSON.stringify(formParam));
                router.push({ path: "/contract/aiccFixtureNote", query: { showForm: true, isFreight: isFreight.value } });
            } else {
                localStorage.setItem("RECORD_DATA", JSON.stringify(formParam));
                const url= isFreight.value ? '/freightForward/fixtureNote' : '/contract/fixtureNote'
                router.push({ path: url, query: { showForm: true, isFreight: isFreight.value,fixtureNo: formParam.fixtureNo } });
            }

        }
    }

    const copyText = code => {
        if (!code) return;
        const oInput = document.createElement("textarea");
        oInput.value = code;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        ElMessage({
            message: "Copy Success",
            type: "success"
        });
        oInput.remove();
    };
</script>
<style lang="scss" scoped>
    .add-container {
        padding-top: 30px;
        background-color: #fafafa;
        height: 100%;
    }

    .form-container {
        margin: auto;
        padding: 40px;
        width: 800px;
        background-color: #fff;
    }

    .dialog-footer {
        margin: 60px auto 0;
        width: 100%;
        text-align: center;
    }

    .booking-no {
        padding: 30px 0 20px;
        text-align: center;

        .fixtureNo,
        span {
            font-size: 30px;
            font-weight: 700;
            padding-right: 4px;
        }

        .fixtureNo {
            margin-top: -10px;
        }
    }
</style>